<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.1.1.js"></script>
    <script src="js/base.js"></script>
</head>
<body>
    <!-- 前端如何把一个图片变成base64  -->
    <input id="file" type="file" />
    <img src="" id="icon" style="width: 200px;height: 200px;"/>
    <button onclick="onSubmitClick();">确认上传</button>
    <script>
        document.getElementById("file").onchange=function(){
            let oFReader = new FileReader();
            oFReader.readAsDataURL(this.files[0]);
            oFReader.onload = function (oFREvent) {
                //alert(oFREvent.target.result);
                //img设置base64数据的前缀："data:image/jpeg;base64,"
                document.getElementById("icon").src=oFREvent.target.result;
            };
        }
        function onSubmitClick() {
            let requestJSON={};
            //如果前端选择的图片是png
            //src的头将会是"data:image/png;base64," .length  =22
            //如果选择jpg
            //src的头将会是"data:image/jpeg;base64," .length  =23
            let src=document.getElementById("icon").src;
            let base64=document.getElementById("icon").src.substring(src.indexOf(",")+1);
            requestJSON.base64=base64;
            $.rest("post","http://localhost:8080/user/icon",requestJSON,function(result){
                if(result.code==200){
                    alert("上传成功");
                }else{
                    alert("上传失败");
                }
            });
        }
    </script>
</body>
</html>